package com.quanyan.place.web;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.TbBizPlaceCategory;
import com.quanyan.place.entity.TbCommonParameter;
import com.quanyan.place.entity.apireq.ReqPlaceCreateCombinedUnit;
import com.quanyan.place.entity.apireq.ReqPlaceDeleteCombinedUnit;
import com.quanyan.place.entity.apireq.ReqPlaceUpdateCombinedUnit;
import com.quanyan.place.entity.vo.PlaceUnitSalePlan;
import com.quanyan.place.entity.vo.PlaceUnitSalePlanVo;
import com.quanyan.place.service.BaseService;
import com.quanyan.place.service.PlaceBaseService;
import com.quanyan.place.service.PlaceInnerService;
import com.quanyan.place.service.PlaceUnitCombineService;
import com.quanyan.place.utils.PlaceUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;

/**
 * Created by yuanxuebing on 16/11/14.
 */
@RestController
@RequestMapping("/admin/api/unitCombine")
public class PlaceUnitCombineController {

    @Autowired
    private PlaceUnitCombineService placeUCService;

    @Autowired
    PlaceInnerService placeService;

    @Autowired
    BaseService baseService;

    @Autowired
    PlaceBaseService placeBaseService;

    /**
     * 获取组合场地详情
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/getCombinedUnitById", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<?> getCombinedUnitById(@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult)  {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        Integer cuId =  MapUtils.getInteger(map, "cuId");
        if (StringUtils.isEmpty(cuId)){
            return APIResponse.returnFail("组合场地id为空！");
        }

        APIResponse apiResponse = placeUCService.getCombinedUnitById(cuId);
        return apiResponse;
    }

    /**
     * 场地组合列表
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/listCombinedUnits", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<?> listCombinedUnits(@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult)  {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        Integer placeId =  MapUtils.getInteger(map, "placeId");
        Integer cateId = MapUtils.getInteger(map, "categoryId");
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId！");
        }
        if (StringUtils.isEmpty(cateId)){
            return APIResponse.returnFail("cateId为空！");
        }

        APIResponse apiResponse = placeUCService.listCombinedUnits(placeId, cateId);
        return apiResponse;
    }

    /**
     * 罗列还未被组合的"子场地"
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/listUncombinedSubUnits", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<?> listUncombinedSubUnits(@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult)  {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        Integer placeId =  MapUtils.getInteger(map, "placeId");
        Integer cateId = MapUtils.getInteger(map, "categoryId");
        String scale = MapUtils.getString(map, "scale");

        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId！");
        }
        if (StringUtils.isEmpty(cateId)){
            return APIResponse.returnFail("cateId为空！");
        }
        if (StringUtils.isEmpty(scale)){
            return APIResponse.returnFail("scale为空！");
        }

        APIResponse apiResponse = placeUCService.listUncombinedSubUnits(placeId, cateId, scale);
        return apiResponse;
    }


    /**
     * 创建新的组合场地
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/createCombinedUnit", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<?> createCombinedUnit(@RequestBody @Valid ReqPlaceCreateCombinedUnit reqCreateCU, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        APIResponse apiResponse = null;
        try {
            apiResponse = placeUCService.createCombinedUnit(reqCreateCU);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail("创建失败:" + e.toString());
        }
        return apiResponse;
    }

    /**
     * 删除组合场地
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/deleteCombinedUnit", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<?> deleteCombinedUnit(@RequestBody @Valid ReqPlaceDeleteCombinedUnit reqDeleteCU, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        APIResponse apiResponse = null;
        try {
            apiResponse = placeUCService.deleteCombinedUnit(reqDeleteCU);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail("删除失败:" + e.toString());
        }
        return apiResponse;
    }

    /**
     * 修改组合场地基本信息
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateCombinedUnit", method = RequestMethod.POST)
    @ResponseBody
    public APIResponse<?> createCombinedUnit(@RequestBody @Valid ReqPlaceUpdateCombinedUnit reqUpdateCU, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        APIResponse apiResponse = null;
        try {
            apiResponse = placeUCService.updateCombinedUnit(reqUpdateCU);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail("创建失败:" + e.toString());
        }
        return apiResponse;
    }

    /**
     * 获取组合场馆销售计划
     * @param placeId
     * @param categoryId
     * @return
     */
    @RequestMapping(value = "/getPlaceInfoForPricing")
    public APIResponse<?> getPlaceInfoForPricing(@RequestParam(value = "placeId",required = true) Integer placeId,
                                                 @RequestParam(value = "categoryId",required = false) Byte categoryId) {

        TbBizPlaceCategory placeCategory = placeBaseService.getPlaceCategory(placeId, Integer.valueOf(categoryId));
        int intervalTime = PlaceUtil.getTimeInterval(placeCategory.getMinSaleTimeUnit());
        List<PlaceUnitSalePlan> result = placeService.getPlaceCombinedUnitSalePlan(placeId, categoryId, intervalTime);
        return APIResponse.returnSuccess(result);
    }


    /**
     * 保存组合场地销售计划(单个)
     * @param placeUnitSalePlan
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/savePlaceSalePlanSingle", method = RequestMethod.POST)
    public APIResponse<PlaceUnitSalePlan> savePlaceSalePlanSingle(@RequestBody @Valid PlaceUnitSalePlan placeUnitSalePlan, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_PLACE_SALEPLAN_SYNC_PERIOD.getCode());
        int period = PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD;  // 需要同步的周期
        if (parameter != null && parameter.getParameterValue() != null){
            period = Integer.valueOf(parameter.getParameterValue());
        }
        List<String> errorMessage = placeService.saveSinglePlaceSalePlan(placeUnitSalePlan,period, UNIT_TYPE_COMBINE);
        if (null != placeUnitSalePlan && null != placeUnitSalePlan.getPlaceId()){
//            // 更新最低价
//            placeInnerService.getMinPrice(placeUnitSalePlan);
//            // 将placeId放入缓存，用于批量更新到solr服务器
//            placeWrapper.setPlaceIdToCache(placeUnitSalePlan.getPlaceId(), placeRedisTemplate);
        }
        if (errorMessage.size() > 0){
            return APIResponse.returnFail(errorMessage.toString());
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 保存组合场地销售计划(批量)
     * @param placeUnitSalePlanVo
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/savePlaceSalePlanBatch", method = RequestMethod.POST)
    public APIResponse<?> savePlaceSalePlanBatch(@RequestBody @Valid PlaceUnitSalePlanVo placeUnitSalePlanVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_PLACE_SALEPLAN_SYNC_PERIOD.getCode());
        int period = PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD;  // 需要同步的周期
        if (parameter != null && parameter.getParameterValue() != null){
            period = Integer.valueOf(parameter.getParameterValue());
        }
        List<String> errorMessage = placeService.savePlaceSalePlanBatch(placeUnitSalePlanVo.getSalePlanList(), period, UNIT_TYPE_COMBINE);

        if (null != placeUnitSalePlanVo && null != placeUnitSalePlanVo.getPlaceId()){
//            // 更新最低价
//            PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
//            placeUnitSalePlan.setPlaceId(placeUnitSalePlanVo.getPlaceId());
//            placeUnitSalePlan.setCategoryId(placeUnitSalePlanVo.getCategoryId().intValue());
//            placeInnerService.getMinPrice(placeUnitSalePlan);
//            // 将placeId放入缓存，用于批量更新到solr服务器
//            placeWrapper.setPlaceIdToCache(placeUnitSalePlanVo.getPlaceId(), placeRedisTemplate);
        }
        if (errorMessage.size() > 0){
            return APIResponse.returnFail(errorMessage.toString());
        }
        return APIResponse.returnSuccess();
    }
}
